package com.zhuannimei.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.xxhong.znm.offers.OffersManager;
import com.zhuannimei.GlobalApplication;
import com.zhuannimei.R;
import com.zhuannimei.adapter.AppAdapter;
import com.zhuannimei.domain.Product;
import com.zhuannimei.domain.Promotion;
import com.zhuannimei.domain.ZnmList;
import com.zhuannimei.net.RequestServerData;
import com.zhuannimei.parser.PromotionParser;
import com.zhuannimei.ui.LotteryDetailActivity;
import com.zhuannimei.utility.JsonUtil;
import com.zhuannimei.utility.UiUtil;
import com.zhuannimei.utility.WuLog;
import com.zhuannimei.utility.YouLog;
import com.zhuannimei.view.CustomIndicator;

public class Fragment1 extends BaseFragment {

	private static final String TAG = "Fragment1";

	// ----------------------------------------------------
	// 滑动图片的集合
	private ViewPager mViewPager;
	private TextView mSlideTitle;
	// ---------------------------------------------------
	private CustomIndicator indicator;
	private String mTimeStamp = "1";// 时间戳

	private ListView mLvApps;
	private List<ZnmList> mAppInfos = getZnmlist();

	private List<Promotion> mPromotions = new ArrayList<Promotion>();

	public interface Callbacks {
		public void onFragmentMethodCallBack(String id);
	}

	private static Callbacks mCallbacks = new Callbacks() {
		@Override
		public void onFragmentMethodCallBack(String id) {
		}
	};

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		Log.i("xxhong", "onAttach");
		if (!(activity instanceof Callbacks)) {
			throw new IllegalStateException(
					"Activity must implement fragment's callbacks.");
		}
		mCallbacks = (Callbacks) activity;
	}

	@Override
	public void onStart() {
		super.onStart();
		Log.i("xxhong", "onStart");
		mTitlePane.setTitle("赚你妹");
		mTitlePane.getLeftButton().setVisibility(View.GONE);
		mTitlePane.getLeftButton().setVisibility(View.VISIBLE);
		mTitlePane.setLeftButtonTextAndListener("消息", new OnClickListener() {
			@Override
			public void onClick(View v) {
				WuLog.i(TAG, "消息");
			}
		});
		mTitlePane.getRightButton().setVisibility(View.GONE);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.i("xxhong", "onCreate");
		// 查询数据库数据
		// 访问网络数据
		try {
			mPromotions.clear();
			List<Promotion> list = GlobalApplication.appDB
					.findAll(Promotion.class);
			if (list != null && list.size() != 0) {
				mPromotions.addAll(list);
			}
			getPromotions();
		} catch (Exception e) {
		}

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.i(TAG, "onCreateView");
		View view = inflater.inflate(R.layout.fragment1, container, false);
		// 初始化推广布局
		View promotionView = inflater.inflate(R.layout.promotion, null);
		// ViewPager滑动页
		mViewPager = (ViewPager) promotionView
				.findViewById(R.id.viewPager);
		indicator = (CustomIndicator) promotionView.findViewById(R.id.indicator);
//		mViewPager.setOnPageChangeListener(listener);
		
		// 设置默认的滑动标题
		mSlideTitle = (TextView) promotionView.findViewById(R.id.tvSlideTitle);
		mLvApps = (ListView) view.findViewById(R.id.lv_apps);
		mLvApps.addHeaderView(promotionView);
		mLvApps.setAdapter(new AppAdapter(getActivity(), mAppInfos, mLvApps));
		mLvApps.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position != 0) {
					String appId = mAppInfos.get(position - 1).getId();
					if ("youmi".equals(appId)) {
						OffersManager.getInstance(getActivity())
								.showOffersWall();
					} else if ("dianle".equals(appId)) {
						mCallbacks.onFragmentMethodCallBack("1");
					}
				}
			}
		});
		refreshAd();
		return view;
	}
	private void refreshAd() {
		if(mPromotions.size()>0){
//			initViewPager();
		}else{
			
		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Log.i("xxhong", "onActivityCreated");
	}
	@Override
	public void onResume() {
		super.onResume();
		Log.i("xxhong", "onResume");
	}

	@Override
	public void onPause() {
		super.onPause();
		Log.i("xxhong", "onPause");
	}

	@Override
	public void onStop() {
		Log.i("xxhong", "onStop");
		super.onStop();
	}

	@Override
	public void onDestroyView() {
		Log.i("xxhong", "onDestroyView");
		super.onDestroyView();
	}

	@Override
	public void onDestroy() {
		Log.i("xxhong", "onDestroy");
		super.onDestroy();
	}

	@Override
	public void onDetach() {
		Log.i("xxhong", "onDetach");
		super.onDetach();
	}

	@Override
	protected void initViews() {
		
	}

	@Override
	protected void initEvents() {
	}

	public List<ZnmList> getZnmlist() {
		ArrayList<ZnmList> list = new ArrayList<ZnmList>();
		ZnmList znmList = new ZnmList();
		znmList.setAppName("赚你妹高速赚妹币通道一");
		znmList.setId("youmi");
		ZnmList znmList1 = new ZnmList();
		znmList1.setAppName("赚你妹高速赚妹币通道二");
		znmList1.setId("dianle");
		list.add(znmList);
		list.add(znmList1);
		return list;
	}
/**
 * 获取推广商品的列表
 */
	private void getPromotions() {
		// 解析
		putAsyncTask(new AsyncTask<Void, Void, String>() {

			@Override
			protected String doInBackground(Void... params) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("timestamp", mTimeStamp);
				Map<String, String> map2 = JsonUtil.getJsonMap(map);
				return "";
			}

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				WuLog.i(TAG, "" + result);
				try {
					if (!TextUtils.isEmpty(result)) {
						JSONObject jo = new JSONObject(result);
						String vCode = jo.getString("result_code");
						String desc = jo.getString("desc");
						mTimeStamp = jo.optString("timestamp");
						WuLog.i(TAG, "服务器返回的时间戳" + mTimeStamp);
						if ("0".equals(vCode)) {
							// 解析推广列表
							mPromotions.clear();
							List<Promotion> list = new PromotionParser()
									.parseJSON(result);
							if (list != null && list.size() != 0) {
								mPromotions.addAll(list);
							}
//							initViewPager();
							// 先删后存
							GlobalApplication.appDB.deleteByWhere(
									Product.class, null);
							for (Promotion prods : mPromotions) {
								GlobalApplication.appDB.save(prods);
							}
						}else{
							showCustomToast(desc);
						}
					}
				} catch (Exception e) {
				}
			}

		});
	}
	

	@Override
	protected void initData() {
		WuLog.i(TAG, "执行刷新数据");
		
	}
//	private void initViewPager() {
//		LayoutInflater mLi = LayoutInflater.from(getActivity());
//		final ArrayList<View> views = new ArrayList<View>();
//		indicator.setCount(mPromotions.size());
//		// 将要分页显示的View装入数组中
//		int i =0;
//		for (final Promotion as : mPromotions) {
//			mSlideTitle.setText(mPromotions.get(0).getAddTopic());
//			i++;
//			View view1 = mLi.inflate(R.layout.content, null);
//			ImageView imageView = (ImageView) view1.findViewById(R.id.image_view);
////			imageView.setBackgroundDrawable(getActivity().getResources().getDrawable(R.drawable.ic_launcher));
//			imageLoader.displayImage(as.getAddPhoto(), imageView, options);
//			view1.setOnClickListener(new OnClickListener() {
//				
//				@Override
//				public void onClick(View v) {
//					UiUtil.showToast(as.getAddTopic());
//					Intent intent = new Intent(getActivity(),LotteryDetailActivity.class);
//					intent.putExtra("addType", as.getAddType());
//					intent.putExtra("addId", as.getAddId());
//					startActivity(intent);
//					
//				}
//			});
//			views.add(view1);
//		}
//		
//		PagerAdapter mPagerAdapter = new PagerAdapter() {
//
//			@Override
//			public boolean isViewFromObject(View arg0, Object arg1) {
//				return arg0 == arg1;
//			}
//
//			@Override
//			public int getCount() {
//				return views.size();
//			}
//
//			@Override
//			public void destroyItem(View container, int position, Object object) {
//				((ViewPager) container).removeView(views.get(position));
//			}
//
//			@Override
//			public Object instantiateItem(View container, int position) {
//				((ViewPager) container).addView(views.get(position));
//				return views.get(position);
//			}
//		};
//		mViewPager.setAdapter(mPagerAdapter);
//		
//	}
//	private OnPageChangeListener listener = new OnPageChangeListener() {
//
//		@Override
//		public void onPageSelected(int arg0) {
//			indicator.setCurrentPosition(arg0);
//			
//			String addTopic = mPromotions.get(arg0).getAddTopic();
//			if(!TextUtils.isEmpty(addTopic)){
//				mSlideTitle.setText(addTopic);
//			}
//			
//			
//		}
//
//		@Override
//		public void onPageScrolled(int arg0, float arg1, int arg2) {
//
//		}
//
//		@Override
//		public void onPageScrollStateChanged(int arg0) {
//
//		}
//	};
	
	
	private void requestLottery(final String param1,final String param2,final String param3) {
		// 解析
		putAsyncTask(new AsyncTask<Void, Void, String>() {

			@Override
			protected String doInBackground(Void... params) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("userId", param1);
				map.put("addId", param2);
				map.put("addType", param3);
				Map<String, String> map2 = JsonUtil.getJsonMap(map);
				return RequestServerData.getLottery(map2);
			}

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				YouLog.i(TAG, "" + result);
				try {
					if (!TextUtils.isEmpty(result)) {
						JSONObject jo = new JSONObject(result);
						String vCode = jo.getString("code");
						
						if ("0".equals(vCode)) {
							JSONObject jores =jo.getJSONObject("result");
							String id=jores.optString("id");
							String name=jores.optString("name");
							String photo=jores.optString("photo");
							String point=jores.optString("point");
							String rule=jores.optString("rule");
							String price=jores.optString("price");
							String peoples=jores.optString("peoples");
							String joiners=jores.optString("joiners");
						}else{
							
						}
					}
				} catch (Exception e) {
				}
			}

		});
	}
}
